package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.AlertDialog;
import android.graphics.Point;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;

import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.utils.CommonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LocationUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

/**
 * Descriptions：显示定位的页面
 * <p>
 * Author：ChenME
 * Date：2017/4/26
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_show_location)
public class ShowLocationActivity extends AppBaseActivity {

    @Bean(CommonUtils.class)
    CommonUtils cUtils;

    @ViewById(R.id.mapView)
    MapView mapView;

    @ViewById(R.id.cv_return2CurrentLocation)
    CardView cv_return2CurrentLocation;

    @Extra("endLatLng")
    LatLng endLatLng;

    private ShowLocationActivity _activity;

    private BaiduMap mBaiduMap;//百度地图
    private LocationClient mLocClient;

    private boolean isMapAlreadyLoaded = false;//地图是否已经成功加载
    private boolean isAlreadyGetCurrentLocation = false;//是否已经成功获取到当前位置
    private boolean isFirstAutoZoom = true;//是否第一次自动缩放

    private LatLng currentLatLng;//当前位置

    @AfterViews
    void onPageStart() {
        _activity = this;

        mBaiduMap = mapView.getMap();
        mLocClient = new LocationClient(_activity);

        initAndStartLocation();

        mBaiduMap.setOnMapLoadedCallback(() -> {

            // 设置指南针的位置
            Point compassPoint = mBaiduMap.getCompassPosition();
            mBaiduMap.setCompassPosition(
                    new Point(compassPoint.x - cUtils.dp2px(10), compassPoint.y + cUtils.dp2px(50)));

            cv_return2CurrentLocation.setVisibility(View.VISIBLE);

            isMapAlreadyLoaded = true;
            if (isAlreadyGetCurrentLocation && null != currentLatLng && isFirstAutoZoom) {
                zoom2FitView();
            }
        });

        addEndMaker();

        setBaiduMapListener();
    }

    /**
     * 添加目的地的Maker
     */
    private void addEndMaker() {
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_gcoding);

        //构建MarkerOption，用于在地图上添加Marker
        MarkerOptions option = new MarkerOptions()
                .position(endLatLng)
                .icon(bitmap).title("导航");

        //在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
    }

    /**
     * 初始化并开启定位
     */
    private void initAndStartLocation() {
        LocationUtil.initLocationClient(mLocClient, 5);

        // 显示缩放控件
        mapView.showZoomControls(true);

        MyLocationConfiguration.LocationMode mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        mLocClient.registerLocationListener(location -> {
            if (null == location) {
                return;
            }

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    .direction(5000).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            isAlreadyGetCurrentLocation = true;
            if (isMapAlreadyLoaded && null != endLatLng && isFirstAutoZoom) {
                zoom2FitView();
            }
        });
        mLocClient.start();
    }

    /**
     * 设置Baidu地图的监听事件
     */
    private void setBaiduMapListener() {
        mBaiduMap.setOnMarkerClickListener(marker -> {
            Button button = new Button(_activity);
            button.setBackgroundResource(R.drawable.rect_transparent_black_with_gray_stroke);
            button.setTextColor(getResources().getColorStateList(R.color.color_defaultTextLighter));
            button.setTextSize(18);
            button.setText(marker.getTitle());
            button.setOnClickListener(v -> {
                mBaiduMap.hideInfoWindow();
                try {
                    if (null == currentLatLng) {
                        showLocationErrDialog();
                        return;
                    }

                    // 构建 导航参数
                    NaviParaOption para = new NaviParaOption()
                            .startPoint(currentLatLng).endPoint(endLatLng);
                    BaiduMapNavigation.openBaiduMapNavi(para, this);
                } catch (BaiduMapAppNotSupportNaviException e) {
                    e.printStackTrace();
                    showBaiduMapErrDialog(this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            LatLng markerLatlng = marker.getPosition();
            InfoWindow mInfoWindow = new InfoWindow(button, markerLatlng, -70);
            mBaiduMap.showInfoWindow(mInfoWindow);
            return true;
        });

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mBaiduMap.hideInfoWindow();
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    /**
     * 显示导航时定位失败的提示
     */
    private void showLocationErrDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("抱歉，未获取到当前定位！请稍后重试！")
                .setNegativeButton("确定", (dialogInterface, i) -> {
                })
                .show();
    }

    /**
     * 缩放到合适大小
     */
    private void zoom2FitView() {
        LatLngBounds llb = new LatLngBounds.Builder().include(endLatLng).include(currentLatLng).build();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(llb));
        isFirstAutoZoom = false;
    }

    /**
     * 点击缩放到合适大小按钮
     */
    @Click(R.id.cv_return2CurrentLocation)
    void zoom2FitViewClick() {
        if (isMapAlreadyLoaded
                && isAlreadyGetCurrentLocation
                && null != currentLatLng
                && null != endLatLng) {
            zoom2FitView();
        }
    }

    /**
     * 退出
     */
    @Click(R.id.cv_backBtn)
    void back() {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocClient.stop();
        mBaiduMap.setMyLocationEnabled(false); // 关闭定位图层
        mapView.onDestroy();
        animUtils.leftOutAnimation(_activity);
    }
}